/// Tenant controller
/// ----------------------------------------------------
/// @Project :   xinhou-rocket-admin
/// @File    :   tenant_controller.rs
/// @Contact :   sp_hrz@qq.com
///
/// @Modify Time      @Author    @Version    @Description
/// ------------      -------    --------    -----------
/// 2024/07/04 17:43   shenpeng   1.0         None

use std::sync::Arc;
use rocket::serde::json::Json;
use rocket::State;
use rocket_okapi::openapi;
use sqlx::MySqlPool;
use crate::business::entity::tenant::Tenant;
use crate::business::service::tenant_service::TenantService;
use crate::extends::core::context::app_context_beans::AppContextBeans;
use crate::extends::core::errors::response_code_enums::ResponseCodeEnum;
use crate::extends::core::http::request_headers::RequestHeaders;
use crate::extends::core::pager::page_helper::PageHelper;
use crate::extends::core::response::reponse_data::R;
use crate::extends::core::response::result_data::ResultData;


#[openapi(tag = "租户管理")]
#[post("/admin/tenant/list", data = "<search>")]
pub async fn list(
    // headers: RequestHeaders,
    search: Json<PageHelper<Tenant>>,
    ctx_beans: &State<AppContextBeans>
) -> Json<R<ResultData<Tenant>>> {
    // 使用提取的头部参数
    // headers.print();
    // 获取 tenant_service 并在失败时引发错误
    let tenant_service: Arc<TenantService> = match ctx_beans.get_bean("tenant_service") {
        Ok(service) => service,
        Err(err) => {
            log::error!("Failed to retrieve tenant_service: {}", err);
            return R::error(ResponseCodeEnum::INTERNAL_SERVER_ERROR); // 返回合适的错误响应
        }
    };
    let result = tenant_service.find(&search).await;
    R::success(Some(result))
}

#[openapi(tag = "租户管理")]
#[get("/admin/tenant/detail/<id>")]
pub async fn detail(id: i32, pool: &State<MySqlPool>) -> Json<R<Tenant>> {
    match Tenant::find_by_id(&id, pool.inner()).await {
        Some(tenant) => R::success(Some(tenant)),
        None => R::error(ResponseCodeEnum::ID_NOT_FOUND),
    }
}

#[openapi(tag = "租户管理")]
#[post("/admin/tenant/save", data = "<tenant>")]
pub async fn save(tenant: Json<Tenant>, pool: &State<MySqlPool>) -> Json<R<i32>> {
    match Tenant::save(&tenant, pool.inner()).await {
        Some(id) => R::success(Some(id)),
        None => R::error(ResponseCodeEnum::INSERT_ERROR),
    }
}

#[openapi(tag = "租户管理")]
#[post("/admin/tenant/update", data = "<tenant>")]
pub async fn update(tenant: Json<Tenant>, pool: &State<MySqlPool>) -> Json<R<bool>> {
    match Tenant::update(&tenant, pool.inner()).await {
        Some(success) => R::success(Some(success)),
        None => R::error(ResponseCodeEnum::UPDATE_ERROR),
    }
}

#[openapi(tag = "租户管理")]
#[get("/admin/tenant/delete/<id>")]
pub async fn delete(id: i32, pool: &State<MySqlPool>) -> Json<R<bool>> {
    match Tenant::delete(&id, pool.inner()).await {
        Some(success) => R::success(Some(success)),
        None => R::error(ResponseCodeEnum::DELETE_ERROR),
    }
}





